// pages/goodsDetail/goodsDetail.js

import {
  get_open_id,
  user_login
} from "../../utils/api.js";
var app = getApp();
var showShareStatus = 0;
var share_uid = 0
var log_status=0;
var goods_title = '';
var carte_name=''
Page({
  /**
   * 页面的初始数据
   */
  data: {
    my_goods: 0,

    posit: '-1',
    pingjia: [],
    yh_pjia: '0',
    gg_yiny: false,
    goodsId: '',
    title: '',
    goodsname: '',
    price: '',
    old_price: '',
    integral_price: '',
    is_integral: 0,
    mount: '',
    goodsNum: '',
    intro_img: '',
    goodsIdList: [],
    mountList: [],
    turn_img: [],
    isSwiperAutoPlay: !0,
    isPlayVideo: !1,
    fullScreen: false,
    isimage: false,
    isvideo: false,
    mdc_video: 'http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400',
    //替换视频的封面图
    mdc_videofenmian: '../../images/house.png',
    TaskShow: 0,
    phoneShow: 0,
    phone: '',
    code: '',
    codePlace: '获取验证码',
    setInter: '',
    content: '',
    mid: 0,
    //微信小程序动画
    animationData: {},
    animationisno: false,
    guilist: {},
    arrId: [],
    arrName: [],
    textStates: ["view-btns-text-normal", "view-btns-text-select"],
    min: 1, //最小值 整数类型，null表示不设置
    max: null, //最大值 整数类型，null表示不设置
    num: 1, //输入框数量 整数类型
    change: 1, //加减变化量 整数类型
    def_num: 1, //输入框值出现异常默认设置值
    spec_status: 0,
    //数据格式
    goods_spec_list: [],
    spec_goods_price: [],
    goods_attr_list: [],
    comment: [],
    fxTaskShow: 0,
    examine_status: 0,
    share_qrcode_img:'',
    hbshow:true,
    openSettingShow: false,
    saveBtnShow: true,
    fangwname:'',
  },
  changeStatus: function() {
    showShareStatus = 0
    this.setData({
      fxTaskShow: 0
    });
  },
  // 选择规格页面弹出   微信小程序动画
  guigeselect: function() {
    let that = this;
    let animal1 = wx.createAnimation({
      timingFunction: 'ease-in'
    }).translate(0, -600).step({
      duration: 500
    })
    that.setData({
      animationData: animal1.export(),
      gg_yiny: true
    })
  },
  // 选择规格页面隐藏   微信小程序动画
  guigeno: function() {
    let that = this
    let animal1 = wx.createAnimation({
      timingFunction: 'ease-in'
    }).translate(0, 600).step({
      duration: 500
    })
    that.setData({
      animationData: animal1.export(),
      gg_yiny: false
    })
  },
  //输入框失去焦点事件
  evblur: function(e) {
    var zval = parseInt(e.detail.value);
    // console.log(zval)
    //正则 正整数 0 负整数
    var goodsNum = this.data.goodsNum
    console.log('测试' + goodsNum)
    if (/(^-[1-9][0-9]{0,}$)|(^0$)|(^[1-9][0-9]{0,}$)/.test(zval)) {
      //最大值
      if (this.data.max != null) {
        if (zval > this.data.max) {
          
          
          this.setData({
            num: this.data.def_num
          })
        } else {
          this.setData({
            num: zval
          })
        };
      } else {
        this.setData({
          num: zval
        })
      };
      //最小值
      if (this.data.min != null) {
        if (zval < this.data.min) {
          console.log("低于最小值")
          this.setData({
            num: this.data.def_num
          })
        } else {
          this.setData({
            num: zval
          })
        };
      } else {
        this.setData({
          num: zval
        })
      };
    } else {
      console.log("不是整数")
      this.setData({
        num: this.data.def_num
      })
    };
  },
  //加
  evad: function() {
    var cval = Number(this.data.num) + this.data.change;
    if (this.data.max != null) {
      if (cval > this.data.max) {
        console.log("超出最大值")
      } else {
        this.setData({
          num: cval
        })
      };
    } else {
      this.setData({
        num: cval
      })
    };
  },
  //减
  evic: function() {
    var cval = Number(this.data.num) - this.data.change;
    if (this.data.min != null) {
      if (cval < this.data.min) {
        console.log("低于最小值")
      } else {
        this.setData({
          num: cval
        })
      };
    } else {
      this.setData({
        num: cval
      })
    };
  },
  // 全屏展示图片
  showPicture: function(e) {
    // console.log(e)
    let img_src = e.currentTarget.dataset.src
    wx.previewImage({
      current: img_src, // 当前显示图片的http链接
      urls: [img_src] // 需要预览的图片http链接列表
    })
  },
  //跳转全部评价
  bindpingjia: function() {
    // console.log(this.data.goodsId);
    wx.navigateTo({
      url: '../../shopPages/AllPjia/AllPjia?goods_id=' + this.data.goodsId,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // console.log(app.globalData.SwitchTabParams.v_id);
    wx.hideShareMenu()
    var that = this;
    if (options.share_id && options.carte_id) {
      // 通过分享链接进入
      app.globalData.shareOptions = {
        share_id: options.share_id,
        carte_id: options.carte_id,
      }
      share_uid = options.share_id
      that.setData({

        mid: options.carte_id
      })
      app.globalData.SwitchTabParams.v_id = options.carte_id;
    }else if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      //&是我们定义的参数链接方式
      console.log(">>>>");
      console.log(scene);
      console.log(">>>>");
      // 通过二维码进入
      app.globalData.shareOptions = {
        share_id: options.scene.split("-")[2],
        carte_id: options.scene.split("-")[1],
      }
      share_uid = options.scene.split("-")[2]
      that.setData({

        mid: options.scene.split("-")[1]
      })
      app.globalData.SwitchTabParams.v_id = options.scene.split("-")[1];
    }else {
      share_uid = 0;
    }
    app.globalData.share_uid = share_uid;
    if (options.id){
      var id = options.id;
    } else if (options.scene){
      var id = options.scene.split("-")[0]
    }
    
    var goodsId = [];
    var mount = [];
    var that = this;
    var url2 = '/shop/goodsDetails';
    var params2 = {
      id: id
    };
    app.HttpGetSend(url2, params2, function(res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        goodsId.push(res.data.id);
        var goodsIdList = goodsId;
        mount.push(1);
        var mountList = mount;

        var turn_img = [];
        for (let i = 0; i < res.data.turn_img.length; i++) {
          if (res.data.turn_img[i].indexOf(".mp4") != -1) {
            var obj = {};
            obj.url = res.data.turn_img[i];
            obj.type = 2;
            turn_img.push(obj);
            that.setData({
              isvideo: true,
              mdc_videofenmian: res.data.face_img,
              mdc_video: res.data.turn_img[i]
            })
          } else {
            var obj = {};
            obj.url = res.data.turn_img[i];
            obj.type = 1;
            turn_img.push(obj);
          }
        }
        that.setData({
          bv_id: res.data.carte_id
        })
        // app.globalData.SwitchTabParams.v_id = res.data.carte_id;
        // console.log(res.data.carte_id+'...');
        // console.log(res)

        console.log(res.data.examine_status);
        if (options.share_id && options.carte_id) {

        } else {
          app.globalData.SwitchTabParams.v_id = res.data.carte_id;
        }
        goods_title = res.data.title
        carte_name = res.data.carte_name
        
        that.setData({
          goods_uid: res.data.carte_id,
          mid: res.data.carte_id,
          goodsId: res.data.id,
          title: res.data.title,
          goodsname: res.data.title,
          price: res.data.price,
          old_price: res.data.old_price,
          mount: res.data.mount,
          goodsNum: res.data.remain_mount,
          intro_img: res.data.intro_img,
          mdc_videofenmian: res.data.face_img,
          turn_img: turn_img,
          goodsIdList: goodsIdList,
          mountList: mountList,
          integral_price: res.data.integral_price,
          is_integral: res.data.is_integral,
          face_img_: res.data.face_img_,
          goods_spec: res.data.goods_spec_list,
          spec_goods_price: res.data.spec_goods_price,
          spec_status: res.data.spec_status,
          comment_count: res.data.comment_count,
          comment: res.data.comment,
          sharecontent: res.data.share_title,
          temp_type: res.data.temp_type,
          content: res.data.describee,
          commission_rate: res.data.commission_rate,
          examine_status: res.data.examine_status,
          limited_status: res.data.limited_status,
          limited_type: res.data.limited_type,
          limited_num: res.data.limited_num,
          fangwname: res.data.carte_name
          // share_qrcode_img: res.data.share_qrcode_img
        })
        that.log()
      }
    }, 1);
  },
  hb_hidden:function(){
    this.setData({
      hbshow: true
    })
  },
  scCanvas:function(){
    var that = this;
    var url = "/shop/get_goods_qrcode";
    app.HttpPostSend(url, {
      uid: app.globalData.userInfo.id,
      id: that.data.goodsId,
    },
      function (result_data) {
        if (result_data.msg != "success") {
          app.showTipMsg(result_data.msg);
        } else {
          that.setData({
            hbshow: false,
            share_qrcode_img: result_data.data
          })
          that.getAvaterInfo();
          
        }
      }
    )
    
  },
  /**
 * 先下载封面图片
 */
  getAvaterInfo: function () {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    });
    var that = this;
    wx.downloadFile({
      url: that.data.mdc_videofenmian, //头像图片路径
      success: function (res) {
        wx.hideLoading();
        if (res.statusCode === 200) {
          console.log(res.tempFilePath)
          var avaterSrc = res.tempFilePath; //下载成功返回结果
          that.getQrCode(avaterSrc); //继续下载二维码图片
        } else {
            wx.showToast({
              title: '头像下载失败！',
              icon: 'none',
              duration: 2000,
              success: function () {
                var avaterSrc = "";
                that.getQrCode(avaterSrc);
              }
            })
        }
      },
      fail:function(){
        setTimeout(function () {
          wx.showToast({
            title: '头像下载失败！',
            icon: 'none',
            duration: 2000,
            success: function () {
              var avaterSrc = "";
              that.getQrCode(avaterSrc);
            }
          })
        }, 10000)
      }
    })
  },

  /**
   * 下载二维码图片
   */
  getQrCode: function (avaterSrc) {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    });
    var that = this;
    wx.downloadFile({
      url: that.data.share_qrcode_img, //二维码路径
      success: function (res) {
        wx.hideLoading();
        console.log(res.tempFilePath)
        if (res.statusCode === 200) {
          var codeSrc = res.tempFilePath;
          that.sharePosteCanvas(avaterSrc, codeSrc);
        } else {
          wx.showToast({
            title: '二维码下载失败！',
            icon: 'none',
            duration: 2000,
            success: function () {
              var codeSrc = "";
              that.sharePosteCanvas(avaterSrc, codeSrc);
            }
          })
        }
      }
    })
  },

  /**
   * 开始用canvas绘制分享海报
   * @param avaterSrc 下载的头像图片路径
   * @param codeSrc   下载的二维码图片路径
   */
  sharePosteCanvas: function (avaterSrc, codeSrc) {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    var that = this;
    var cardInfo = that.data; //需要绘制的数据集合
    const ctx = wx.createCanvasContext('myCanvas'); //创建画布
    var width = "";
    wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function (rect) {
      var height = rect.height;
      var right = rect.right;
      width = rect.width * 0.8;
      var left = rect.left + 0;
      ctx.setFillStyle('#fff');
      ctx.fillRect(0, 0, rect.width, height);

      //头像为正方形
      if (avaterSrc) {
        ctx.drawImage(avaterSrc, 0, 0, rect.width, rect.width);
        // ctx.setFontSize(14);
        ctx.setFillStyle('#fff');
        ctx.setTextAlign('left');
      }

      //标签
      // if (cardInfo.TagText) {
      //   ctx.fillText(cardInfo.TagText, left + 20, width - 4);
      //   const metrics = ctx.measureText(cardInfo.TagText); //测量文本信息
      //   ctx.stroke();
      //   ctx.rect(left + 10, width - 20, metrics.width + 20, 25);
      //   ctx.setFillStyle('rgba(255,255,255,0.4)');
      //   ctx.fill();
      // }

      //姓名
      if (cardInfo.goodsname) {
        const CONTENT_ROW_LENGTH = 24; // 正文 单行显示字符长度
        let [contentLeng, contentArray, contentRows] = that.textByteLength(cardInfo.goodsname, CONTENT_ROW_LENGTH);
        ctx.setFontSize(14);
        ctx.setFillStyle('#000');
        ctx.setTextAlign('left');
        let contentHh = 22 * 1;
        for (let m = 0; m < contentArray.length; m++) {

          ctx.fillText(contentArray[m],20, width + 95 + contentHh * m);
        }
      }

      var price = '¥'+cardInfo.price
      // 价格
      if (price) {
        const CONTENT_ROW_LENGTH = 24; // 正文 单行显示字符长度
        
        let [contentLeng, contentArray, contentRows] = that.textByteLength(price, CONTENT_ROW_LENGTH);
        ctx.setTextAlign('left');
        ctx.setFillStyle('#FF0039');
        ctx.setFontSize(15);
        ctx.font = 'normal bold 15px sans-serif';
        let contentHh = 22 * 1;
        for (let m = 0; m < contentArray.length; m++) {
          ctx.fillText(contentArray[m], 20, width + 150 + contentHh * m);
        }
      }

      //  绘制二维码
      if (codeSrc) {
        ctx.drawImage(codeSrc, left + 170, width + 80, width / 3, width / 3)
        ctx.setFontSize(10);
        ctx.setFillStyle('#000');
        // ctx.fillText("微信扫码或长按识别", left + 170, width + 180);
      }

    }).exec()

    setTimeout(function () {
      ctx.draw();
      wx.hideLoading();
    }, 1000)

  },

  /**
   * 多行文字处理，每行显示数量
   * @param text 为传入的文本
   * @param num  为单行显示的字节长度
   */
  textByteLength(text, num) {
    let strLength = 0; // text byte length
    let rows = 1;
    let str = 0;
    let arr = [];
    var text = text.substring(0,24)
    for (let j = 0; j < text.length; j++) {
      if (text.charCodeAt(j) > 255) {
        strLength += 2;
        if (strLength > rows * num) {
          strLength++;
          arr.push(text.slice(str, j));
          str = j;
          if (rows == 2 & text.length > 24) {
           var text = text + '...'
          }
          rows++;
        }
      } else {
        strLength++;
        if (strLength > rows * num) {
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      }
    }
    arr.push(text.slice(str, text.length));
    return [strLength, arr, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
  },

  //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          var hbshow = that.data.hbshow
          var task_fx = that.data.task_fx
          that.setData({
            hbshow: true,
            task_fx:false
          })
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              // utils.aiCardActionRecord(19);
              if (app.globalData.SwitchTabParams.v_id != app.globalData.userInfo.id){
                app.radarAdd(app.globalData.SwitchTabParams.v_id, 33, 0, that.data.goodsname, app.globalData.userInfo.logo)
                app.addlog(app.globalData.SwitchTabParams.v_id, carte_name, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 33, goods_title)
              }
              
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
              var openSettingShow = that.data.openSettingShow
              var saveBtnShow = that.data.saveBtnShow
              that.setData({
                openSettingShow: true,
                saveBtnShow: false
              })
            }
          })
        }
      });
    }, 1000);
  },
  //检测授权
  checkUserSetting() {
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.writePhotosAlbum']) {
          // 已经授权
          var openSettingShow = that.data.openSettingShow
          var saveBtnShow = that.data.saveBtnShow
          this.setData({
            openSettingShow : false,
            saveBtnShow :true
          })
        }
      }
    })
  },
  openSetting() {
    var that = this
    wx.openSetting({
      success(settingdata) {
        console.log(settingdata)
        if (settingdata.authSetting["scope.writePhotosAlbum"]) {
          console.log("获取权限成功，再次点击图片保存到相册");
          that.setData({
            openSettingShow: false,
            saveBtnShow: true
          })
        } else {
          console.log("获取权限失败");
        }
      }
    })
  },
  selectGuige(e) {
    let that = this,
      // 获取第一个循环的index
      fuindex = e.currentTarget.dataset.fuindex,
      // 获取第二个循环的index
      chindex = e.currentTarget.dataset.chindex,
      // 获取当前点击的id
      selectId = e.currentTarget.dataset.id,
      // 获取当前点击的规格名称
      selectName = e.currentTarget.dataset.item,
      //  初始化arrId
      arrId = that.data.arrId,
      //  初始化arrName
      arrName = that.data.arrName,
      guilists = {},
      goods_spec = that.data.goods_spec;

    // 通过循环来判断点击了哪一个规格，根据数据结构来；
    // goods_spec[fuindex]根据fuindex来判断点击了哪一种类型的规格
    for (let i = 0; i < goods_spec[fuindex].length; i++) {
      // 当i等于当前点击的规格时，设置isClick=1
      if (i == chindex) {
        goods_spec[fuindex][i].isClick = 1;
      }
      // 否则设置其他的isClick=0
      else {
        goods_spec[fuindex][i].isClick = 0;
      }
    };
    // 把点击的规格名称和规格id存起来
    arrId[fuindex] = selectId;
    arrName[fuindex] = selectName;

    // 拼接规格id，（后台返回的数据是这个）
    let selectGuigeId = arrId.join('_');
    for (let i = 0; i < that.data.spec_goods_price.length; i++) {
      // 找对应的规格组合
      if (that.data.spec_goods_price[i].key == selectGuigeId) {
        guilists = that.data.spec_goods_price[i];
      }
    }
    // console.log(guilists);
    that.setData({
      goods_spec: goods_spec,
      arrId,
      guilist: guilists,
      selectGuigeName: arrName
    })
  },
  numChange(e) {
    this.setData({
      num: e.detail.value
    })
  },
  queDing() {
    let that = this;
    let selectguigeid = that.data.arrId.join('_');
    for (let i = 0; i < that.data.spec_goods_price.length; i++) {
      // 判断是否选择规格
      if (that.data.spec_goods_price[i].key == selectguigeid) {
        wx.showModal({
          showCancel: false,
          content: '选择成功',
          success: function(res) {}
        });
        // 判断库存是否充足
        if (selectguigeid.store_count <= 0) {
          wx.showModal({
            showCancel: false,
            content: '库存不足',
            success: function(res) {}
          });
        }
        // 两种情况满足跳转
        else {
          wx.showModal({
            showCancel: false,
            content: '跳转页面',
            success: function(res) {}
          });
        }
        return
      } else {
        wx.showModal({
          showCancel: false,
          content: '请选择规格',
          success: function(res) {
            if (res.confirm) {}
          }
        })
      }
    }
  },
  share_integral: function() {
    var url2 = "/shop/to_share";
    var params2 = {
      type: 1,
      uid: app.globalData.shareOptions.share_id,
      tuid: app.globalData.userInfo.id

    }
    app.HttpPostSend(url2, params2,
      function(result_data) {
        // console.log(result_data.data)

      })
  },
  // 检测是否需要登录
  checkUserInfo: function() {
    const that = this
  
    let openid = wx.getStorageSync('openid')
    console.log(openid);
    if (openid) {
      app.globalData.openid = openid
      that.setData({
        openid,
      })
      let url = '/user_api/getInfoByOpenID';
      app.HttpPostSend(
        url, {
          openid: openid,
          invite_id: share_uid,
        },
        function(result_data) {
          if (result_data === '-10000') {
            that.setData({
              TaskShow: 1
            });
            return false;
          }
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            if (!!result_data.data) { //如果后台有数据
              app.globalData.userInfo = {
                ...result_data.data
              }
              wx.setStorage({
                key: 'userInfo',
                data: JSON.stringify({
                  ...result_data.data
                })
              })
              if (that.data.goods_uid == result_data.data.id) {
                that.setData({
                  my_goods: 1
                });
              }
              that.log()
              that.share_integral()
            } else { //如果后台无数据
              wx.login({
                success(res) {
                  let params = {
                    code: res.code
                  }
                  app.HttpGetSend(get_open_id, params, function(result) {

                    if (result.msg != "success") {
                      app.showTipMsg(result.msg);
                    } else {
                      app.globalData.openid = result.data.openid.openid;
                      app.globalData.userInfo = result.data.userinfo;
                      if (that.data.goods_uid == result.data.userinfo.id) {
                        that.setData({
                          my_goods: 1
                        });
                      }
                      wx.setStorage({
                        key: 'openid',
                        data: result.data.openid.openid
                      })
                      that.setData({
                        openid: result.data.openid.openid
                      })
                      that.setData({
                        TaskShow: 1,
                        openid: result.data.openid.openid
                      })
                      that.log()
                      that.share_integral()
                    }
                  }, 1)
                }
              })
            }
          }
        })
    } else {

      wx.login({
        success(res) {
          let params = {
            code: res.code,
            invite_id: share_uid,
          }
          app.HttpGetSend(get_open_id, params, function(result) {

            if (result.msg != "success") {
              app.showTipMsg(result.msg);
            } else {
              app.globalData.openid = result.data.openid.openid;
              app.globalData.userInfo = result.data.userinfo;
              if (that.data.goods_uid == result.data.userinfo.id) {
                that.setData({
                  my_goods: 1
                });
              }
              wx.setStorage({
                key: 'openid',
                data: result.data.openid.openid
              })
              that.setData({
                openid: result.data.openid.openid
              })
              that.setData({
                TaskShow: 1,
                openid: result.data.openid.openid
              })
              that.log()
              that.share_integral()
            }
          }, 1)
        },
        fail: function(res) {
          console.log('失败');
        }
      })
    }
    let systemInfo = wx.getSystemInfoSync()
    app.globalData.systemInfo = systemInfo
    this.setData({
      systemInfo
    })
  },


  // 获取用户信息
  bindGetUserInfo: function(e) {
    const that = this
    let userInfo = e.detail.userInfo
    try {
      app.HttpPostSend(
        user_login, {
          openid: that.data.openid,
          username: userInfo.nickName,
          logo: userInfo.avatarUrl,
          sex: userInfo.gender,
          invite_id: share_uid,
        },
        function(result_data) {
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            app.globalData.authSettingUser = 1;
            let userInfo = {
              ...result_data.data
            }
            app.globalData.userInfo = userInfo
            wx.setStorage({
              key: 'userInfo',
              data: JSON.stringify(userInfo)
            })
            that.log()
            that.setData({
              TaskShow: 0,
              userInfo: userInfo
            })
          }
        })
    } catch (error) {

    }
  },

  //输入手机号
  inputgetPhone: function(e) {
    this.setData({
      phone: e.detail.value
    });
  },

  //输入验证码
  inputgetCode: function(e) {
    this.setData({
      code: e.detail.value
    });
  },

  //获取验证码
  getCode: function(e) {
    const that = this
    if (!app.phoneReg(that.data.phone)) {
      wx.showToast({
        title: '输入正确的手机号',
        icon: 'none',
        duration: 1000
      })

      return false;
    }
    var url = '/ali_msg_api/sendMsg';
    var params = {
      phone: that.data.phone
    };
    app.HttpPostSend(url, params, function(res) {
      if (res.code != "1") {
        app.showTipMsg(res.data);
        that.data.codePlace = "重新发送";
      } else {
        var curCount = 60;
        that.setData({
          codePlace: curCount + "s"
        })
        that.data.setInter = setInterval(function() {
          if (curCount == 1) {
            clearInterval(that.data.setInter);
            that.setData({
              codePlace: "重新发送"
            })
          } else {
            curCount = Number(curCount) - 1;
            that.setData({
              codePlace: curCount + "s"
            })
          }
        }, 1000);
      }
    });
  },

  //关闭手机号弹窗
  closePhoneShow: function(e) {
    this.setData({
      phoneShow: 0
    })
  },

  // 添加手机号
  showAddPhone: function(e) {
    const that = this
    if (!app.phoneReg(that.data.phone)) {
      wx.showToast({
        title: '输入正确的手机号',
        icon: 'none',
        duration: 1000
      })

      return false;
    }
    var url = "/user_api/phoneAuth";
    app.HttpPostSend(url, {
        uid: app.globalData.userInfo.id,
        phone: that.data.phone,
        code: that.data.code
      },
      function(result_data) {
        if (result_data.msg != "success") {
          app.showTipMsg(result_data.msg);
        } else {

          app.globalData.userInfo = {
            ...result_data.data
          }
          wx.setStorage({
            key: 'userInfo',
            data: JSON.stringify({
              ...result_data.data
            })
          })
          that.setData({
            phoneShow: 0,
            userInfo: result_data.data
          })
          clearInterval(that.data.setInter);
          var spec_price_id = 0;
          if (that.data.spec_status > 0) {
            spec_price_id = that.data.guilist.id
          }
          wx.navigateTo({
            url: '../orderSure/orderSure?goodsId=' + that.data.goodsIdList + '&mount=' + that.data.num + '&spec_price_id=' + spec_price_id + '&backType=goods'
          })
        }
      })
  },


  videoPlay: function() {
    this.videoPopSet();
  },
  videoPopSet: function() {
    this.setData({
      isSwiperAutoPlay: !1,
      isPlayVideo: !0
    });
  },
  videoStop: function() {
    this.setData({
      isSwiperAutoPlay: !0,
      isPlayVideo: !1
    });

  },

  /**关闭视屏 */
  closeVideo() {
    //执行退出全屏方法
    this.setData({
      isPlayVideo: !1,
      isSwiperAutoPlay: !0,
    })
  },

  //点击商城图标进入个人商城页面
  bindMyMallTap: function(e) {
    if (this.data.temp_type > 0) {
      wx.navigateTo({
        url: '/shopPages/shopxq/shopxq?mid=' + this.data.mid
      })
    } else {
      wx.navigateTo({
        // url: '../myMall/myMall?mid=' + this.data.mid
        url: '/shopPages/personalShop/personalShop?mid=' + this.data.mid,
      })
    }
  },
  //点击咨询图标进入咨询聊天页面
  bindSocksTap: function(e) {
    if (this.data.my_goods > 0) {
      wx.showModal({
        title: '提示',
        content: '无法与自己聊天',
        showCancel: false,
        success: function() {}
      })
    } else {
      wx.navigateTo({
        url: '../socks/socks?mid=' + this.data.mid
      })
      app.addlog(app.globalData.SwitchTabParams.v_id, carte_name, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 6, '')
    }

  },
  //点击购物车图标进入购物车页面
  bindBuyCarTap: function(e) {
    wx.switchTab({
      url: '../buyCar/buyCar',
    })
    // wx.navigateTo({
    //   url: '../buyCar/buyCar?uid=' + app.globalData.userInfo.id
    // })
  },
  //点击商家图标进商家名片
  showCarte: function(e) {
    app.globalData.SwitchTabParams = {
      v_id: this.data.mid
    }
    wx.switchTab({
      url: '/pages/carteShow/carteShow'
    })
  },
  //点击个人图标进入个人页面
  bindPersonTap: function(e) {
    wx.switchTab({
      url: '/pages/person/person',
    })
  },
  notshare: function() {
    wx.showToast({
      title: '商品审核中',
      icon: 'none',
      duration: 1000
    })
  },
  //点击加入购物车
  bindAddCardTap: function(e) {
    var that = this;
    var goodsname = that.data.goodsname;
    if (that.data.examine_status == 0) {
      wx.showToast({
        title: '商品审核中',
        icon: 'none',
        duration: 1000
      })
      return false;
    }
    if (that.data.spec_status > 0 && that.data.guilist.id == undefined) {
      if (that.data.gg_yiny == true) {
        wx.showToast({
          title: '请选择规格',
          icon: 'none',
          duration: 1000
        })
      } else {
        that.guigeselect();
      }
      return false;
    } else {
      if (that.data.num == 1 && that.data.gg_yiny == false) {
        that.guigeselect();
        return false;
      }

    }
    // console.log(that.data.guilist.id);
    if (that.data.goodsNum < 1 && that.data.spec_status == 0) {
      wx.showToast({
        title: '商品数量不足',
        icon: 'none',
        duration: 1000
      })
      return false;
    } else if (that.data.guilist.id == undefined && that.data.spec_status > 0) {
      wx.showToast({
        title: '请选择规格',
        icon: 'none',
        duration: 1000
      })
      return false;
    } else if (that.data.num > that.data.guilist.store_count && that.data.spec_status > 0) {
      wx.showToast({
        title: '商品数量不足',
        icon: 'none',
        duration: 1000
      })
      return false;
    } else {
      var spec_price_id = 0;
      if (that.data.spec_status > 0) {
        spec_price_id = that.data.guilist.id
        console.log(that.data.guilist);
        goodsname = goodsname + "(" + that.data.guilist.key_name+")"
      }
      var id = e.detail.button_typId;
      var that = this;
      var url2 = '/cart/add_v4';
      var params2 = {
        uid: app.globalData.userInfo.id,
        goods_id: id,
        spec_price_id: spec_price_id,
        num: that.data.num,
        timestamp: new Date().getTime(),
      };
      params2.sign = app.getSign(params2)
      app.HttpGetSend(url2, params2, function(res) {
        if (res.msg != "success") {
          app.showTipMsg(res.msg);
        } else {
          if (app.globalData.SwitchTabParams.v_id != app.globalData.userInfo.id){
            app.addlog(app.globalData.SwitchTabParams.v_id, carte_name, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 31, goods_title)
          }
         
          app.radarAdd(app.globalData.SwitchTabParams.v_id, 31, 0, goodsname, app.globalData.userInfo.logo)
          app.showTipMsg('添加至购物车');
        }
      });

    }
  },
  bindBuyTap: function(e) {
    var that = this;
    if (that.data.examine_status == 0) {
      wx.showToast({
        title: '商品审核中',
        icon: 'none',
        duration: 1000
      })
      return false;
    }

    if (that.data.spec_status > 0 && that.data.guilist.id == undefined) {
      if (that.data.gg_yiny == true) {
        wx.showToast({
          title: '请选择规格',
          icon: 'none',
          duration: 1000
        })
      } else {
        that.guigeselect();
      }
      return false;
    } else {
      if (that.data.num == 1 && that.data.gg_yiny == false) {
        that.guigeselect();
        return false;
      }
    }
    // console.log(that.data.guilist.id);
    if (that.data.goodsNum < 1 && that.data.spec_status == 0) {
      wx.showToast({
        title: '商品数量不足',
        icon: 'none',
        duration: 1000
      })
      return false;
    } else if (that.data.guilist.id == undefined && that.data.spec_status > 0) {
      wx.showToast({
        title: '请选择规格',
        icon: 'none',
        duration: 1000
      })
      return false;
    } else if (that.data.num > that.data.guilist.store_count && that.data.spec_status > 0) {
      wx.showToast({
        title: '商品数量不足!',
        icon: 'none',
        duration: 1000
      })
      return false;
    } else {
      if (!app.globalData.userInfo.phone) {
        this.setData({
          phoneShow: 1
        })
      } else {
        let that = this;
        var spec_price_id = 0;
        if (that.data.spec_status > 0) {
          spec_price_id = that.data.guilist.id
        }
        wx.navigateTo({
          url: '../orderSure/orderSure?goodsId=' + this.data.goodsIdList + '&mount=' + this.data.num + '&spec_price_id=' + spec_price_id + '&backType=goods'
        })
      }
    }
  },

  // 打开分享商品遮罩层
  Showshare: function(e) {
    const that = this
    that.setData({
      task_fx: true
    })
  },

  // 关闭分享遮罩层
  HideShareMask: function() {
    this.setData({
      task_fx: false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    log_status = 1;
    goods_title = '';
    carte_name = '';
    that.checkUserInfo()
    if (showShareStatus > 0) {
      that.setData({
        fxTaskShow: 1,
        isPlayVideo: !1,
        isSwiperAutoPlay: !0,
      });
    }
  },

  log: function() {
    var that = this;
    console.log(goods_title + '....');
    if (app.globalData.userInfo.id != app.globalData.SwitchTabParams.v_id && log_status == 1 && goods_title != '') {
      console.log('发送');
      log_status = 0;
      // 雷达添加查看记录 -产品访问数
      // app.radarAdd(app.globalData.SwitchTabParams.v_id, 13, 0, that.data.title)
      
      app.radarAdd(app.globalData.SwitchTabParams.v_id, 13, 0, goods_title, app.globalData.userInfo.logo)

      // 发送模板消息-访客到访通知
      // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter', '正在浏览' + that.data.title + '商品详情', '', '', '')
      app.addlog(app.globalData.SwitchTabParams.v_id, carte_name, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 13, goods_title)
      
      app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter?coming_status=1', '正在浏览' + goods_title + '商品详情', '', '', '')
    }
    // var url2 = "/cardshop_api/card_word";
    // var params2 = {
    //   type: 2,
    //   // uid: app.globalData.SwitchTabParams.v_id
    //   uid: that.data.bv_id
    // }
    // app.HttpPostSend(url2, params2,
    //     function (result_data) {
    //       // console.log(result_data.data)
    //       if (result_data.msg != "success") {
    //         app.showTipMsg(result_data.msg);
    //       } else {
    //         if (!!result_data.data) {
    //           that.setData({
    //             content: result_data.data.content
    //           })
    //         }
    //       }
    //     })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    var that = this;
    clearInterval(that.data.setInter);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    var that = this;
    clearInterval(that.data.setInter);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */

  onShareAppMessage: function(e) {
    const that = this

    if (app.globalData.SwitchTabParams.v_id != app.globalData.userInfo.id){
      app.radarAdd(app.globalData.SwitchTabParams.v_id, 32, 0, that.data.goodsname, app.globalData.userInfo.logo)
      app.addlog(app.globalData.SwitchTabParams.v_id, carte_name, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 32, goods_title)
    }
    

    if (that.data.sharecontent.indexOf("***") != -1) {
      var sharecontent = that.data.sharecontent.replace('***', goods_title);
    } else {
      var sharecontent = goods_title;
    }
    if (e.from === 'button') {

      // 来自页面内转发按钮
      showShareStatus = 1;
      that.setData({
        task_fx: false
      })
    }
    console.log('/pages/goodsDetail/goodsDetail?carte_id=' + app.globalData.SwitchTabParams.v_id + '&share_id=' + app.globalData.userInfo.id + '&id=' + that.data.goodsId);
    return {
      title: sharecontent,
      desc: '',
      path: '/pages/goodsDetail/goodsDetail?carte_id=' + app.globalData.SwitchTabParams.v_id + '&share_id=' + app.globalData.userInfo.id + '&id=' + that.data.goodsId,
      imageUrl: that.data.mdc_videofenmian,
      success: function() {
       
        // var url2 = "/shop/to_share";
        // var params2 = {
        //   type: 1,
        //   uid: app.globalData.userInfo.id
        // }
        // app.HttpPostSend(url2, params2,
        //     function (result_data) {
        //       // console.log(result_data.data)
        //
        //     })
      },
      complete(res) {
        that.setData({
          task_fx:false,
          TaskShow: 0,
          fxTaskShow: 1,
          isPlayVideo: !1,
          isSwiperAutoPlay: !0,
        })
      }
    }
  },
})